package com.xtaller.easy.admin.controller.base;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.convert.J;
import com.xtaller.common.convert.V;
import com.xtaller.common.convert.W;
import com.xtaller.common.kit.IdKit;
import com.xtaller.easy.admin.base.TApi;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.model.BaseUserLabel;
import com.xtaller.easy.admin.service.impl.BaseUserLabelService;
import com.xtaller.easy.admin.specification.UserLabelOpt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Taller on 2018/5/9
 */
@Api(tags = "用户标签管理api")
@RestController
@RequestMapping("/v1/base")
@CrossOrigin   //跨域服务注解
public class UserLabelApi extends TApi {
    @Autowired
    private BaseUserLabelService labelService;

    private Map<String,String> BaseVerify(){
        Map<String,String> verify = new HashMap<>();
        verify.put("userId","用户id不能为空");
        verify.put("labelId","标签id不能为空");
        return verify;
    }
    @PutMapping("/user-label")
    @ApiOperation(value = "操作标签数据")
    public Object optLabel(@RequestBody UserLabelOpt object){
        JSONObject check = V.checkEmpty(BaseVerify(), object);
        if(check.getBoolean("check"))
            return R.error(check.getString("message"));

        BaseUserLabel label = labelService.queryOne(
                W.f(
                        W.and("userId", "eq", object.getUserId()),
                        W.and("labelId", "eq", object.getLabelId())
                ));
        if(label == null){
            label = J.o2m(object, BaseUserLabel.class);
            label.setId(IdKit.getId(201));
            label = labelService.createBaseUserLabel(label);
        }else{
            label.setVal(object.getVal());
            label = labelService.updateBaseUserLabel(label);
        }
        if(label == null)
            return R.error("标签数据保存失败");
        return R.ok("标签数据保存成功");
    }
}
